<template>
  <div style="width: 100%">
    <a-card class="card" :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :sm="{span:12}" :lg="{span:12}" :xl="{span:6}">
              <a-form-item label="院系">
                <a-select :disabled="selectMenu.yx.length === 1" :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.zsyxm" @change="yxChange">
                  <a-select-option v-for="i in selectMenu.yx" :key="i.id" :value="i.dwh">{{ i.dwh +'-'+i.dwmc }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :sm="{span:12}" :lg="{span:12}" :xl="{span:6}">
              <a-form-item label="专业">
                <a-select :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.zszym" @change="getyjfx()">
                  <a-select-option v-for="i in selectMenu.zy" :key="i.id" :value="i.zyh">{{i.zyh+'-'+ i.zymc }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :sm="{span:12}" :lg="{span:12}" :xl="{span:6}">
                <a-form-item label="学习形式">
                  <a-select :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.isqrz" @change="getyjfx()">
                    <a-select-option v-for="i in selectMenu.xxlx" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :sm="{span:12}" :lg="{span:12}" :xl="{span:6}">
                <a-form-item label="招生年度">
                  <a-select :allowClear="true" v-model="queryParam.zsnj" showSearch optionFilterProp="children" @change="getyjfx()">
                    <a-select-option v-for="i in TYPE0126" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :sm="{span:12}" :lg="{span:12}" :xl="{span:6}">
                <a-form-item label="研究方向">
                  <a-select :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.bkyjfxm" >
                    <a-select-option v-for="i in selectMenu.fx" :key="i.id" :value="i.yjfxm">{{ i.yjfxm.substring(i.yjfxm.length-2) +"-"+ i.yjfxmc }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :sm="{span:24}" :xl="{span:24}" style="text-align:center">
             <a-button type="primary" @click="loadData">查询</a-button>
             <a-button type="primary" @click="handleCreate">添加</a-button>
              <a-button type="primary" @click="handleBatchDel">批量删除</a-button>
             <a-button type="primary" @click="exportExcel">下载导入模板</a-button>
              <a-upload @change='handleImport' :fileList="fileList" :beforeUpload="beforeUpload" :showUploadList='false'>
                <a-button type="primary" :loading="uploading">{{uploading ? 'Uploading' : '导入' }}</a-button>
              </a-upload>
              <a-button @click="queryParam = {};loadData()" style="margin:0 10px">重置</a-button>
              <a @click="advanced = !advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'" />
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card class="card" :bordered="false">
      <a-alert :message="'总条数：' + pagination.total" type="info" show-icon />
      <a-table ref="table" size="default" rowKey="key" :columns="columns" :loading="loading" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :dataSource="data" :pagination="pagination" @change="handleTableChange">
        <template slot="action" slot-scope="text,record">
          <a @click="handleEdit(record.id)">修改</a>
          <a @click="handleDel(record.id)">删除</a>
        </template>
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
      </a-table>
    </a-card>

    <second-fractional-edit :info="secondFractionalEditData" :editVisible="secondFractionalEditVisible" @close="handleEditClose"
      @success="handleEditSuccess"></second-fractional-edit>
    <second-fractional-add  :addVisible="secondFractionalAddVisible" @close="handleEditClose"
      @success="handleAddSuccess"></second-fractional-add>
  </div>
</template>

<script>
  import SecondFractionalEdit from './secondFractionalEdit'
  import SecondFractionalAdd from './secondFractionalAdd'
  // import moment from 'moment'
  import {
    STable
  } from '~'
  import {
    mapState
  } from 'vuex'

  const selectArr = ['TYPE0126', 'TYPE0075', 'TYPE0125', 'TYPE0072']

  export default {
    components: {
      STable,
      SecondFractionalEdit,
      SecondFractionalAdd
    },
    data() {
      return {
        advanced: true,
        secondFractionalEditVisible: false,
        secondFractionalAddVisible:false,
        loading: false,
        uploading: false,
        fileList: [],
        data: [],
        // 查询参数
        queryParam: {
          zsyxm: '',
          zszym: '',
          isqrz: '',
          zsnj:'',
          bkyjfxm: ''
        },
        postParams: {},
        // 表头
        columns: [{
            title: '序号',
            scopedSlots: {
              customRender: 'serial'
            }
          },
          {
            title: '院系名称',
            dataIndex: 'zsyxm'
          },
          {
            title: '学科专业码',
            dataIndex: 'zszym'
          },
           {
            title: '研究方向名称',
            dataIndex: 'yjfxmmc'
          },
          {
            title: '专业名称',
            dataIndex: 'zszymc'
          },
          {
            title: '科目一',
            dataIndex: 'kmyfsx'
          },
          {
            title: '科目二',
            dataIndex: 'kmefsx'
          },
          {
            title: '科目三',
            dataIndex: 'kmsfsx'
          },
          {
            title: '科目四',
            dataIndex: 'kmffsx'
          },
          {
            title: '学习形式',
            dataIndex: 'isqrz'
          },
          {
            title: '总分',
            dataIndex: 'zffsx'
          },
          // {
          //   title: '审核状态',
          //   dataIndex: 'fsxzt'
          // },
          {
            title: '操作',
            dataIndex: 'cz',
            fixed: 'right',
            width: 120,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        selectedRowKeys: [],
        selectedRows: [],
        // custom table alert & rowSelection
        options: {
          alert: {
            show: false
          },
          rowSelection: {
            onChange: (selectedRowKeys, selectedRows) => {
              console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
            },
            onSelect: (record, selected, selectedRows) => {
              console.log(record, selected, selectedRows)
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
              console.log(selected, selectedRows, changeRows)
            }
          }
        },
        selectMenu: {
          yx: [], // 院系
          zy: [],
          xxlx: [],
          fx:[]
        },
        secondFractionalEditData: {},
        pagination: {
          current: 1,
          pageSize:10,
          showTotal: (() => {return `共 ${this.pagination.total} 条`}),
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30','40'],
          // 改变pageSize后触发
          onShowSizeChange: (current, pageSize) => this.pagination.pageSize = pageSize,
        }
      }
    },
    computed: {
      ...mapState({
        systemInfo: state => state.app.systemInfo,
        TYPE0126: state => state.app['TYPE0126'] // 年级
      })
    },
    created() {
      this.initSelectMenu()
      selectArr.forEach(v => {
        this.$store.dispatch('app/setDictionary', v)
      })
    },
    methods: {
      initSelectMenu() {
        let allRequest = [
          this.$api.base.collegeAll()
        ]
        Promise.all(allRequest).then(res => {
          this.selectMenu = {
            yx: res[0].data
          }
          this.queryParam.zsyxm = res[0].data[0].dwh
          this.getProssion(this.queryParam.zsyxm)
         
          // 获取学习形式
          this.$api.base.dictionaryData('TYPE0441').then(res => {
            this.selectMenu.xxlx = res.data
          })
          
           this.$api.base.getSchoolYear().then(res => {
            this.queryParam.zsnj = res.data.masterAdmissionYear
            this.loadData({
              pageSize: 10,
              pageNum: 1
            })
          })
        
        })
      },
      getyjfx(){
        //获取研究方向
        if(this.queryParam.zszym && this.queryParam.zsyxm && this.queryParam.zsnj && this.queryParam.isqrz){
          let params={sszym: this.queryParam.zszym,ssyxm: this.queryParam.zsyxm,xwccm:2,zsxn:this.queryParam.zsnj,qrzhfqrz:this.queryParam.isqrz}
          this.$api.base.researchAll(params).then(res => {
            this.$set(this.selectMenu, 'fx', res.data)
          })
        }
          
      },
       // 加载数据
     loadData(parameter = {}) {
       // console.log(parameter)
       if(!parameter.pageNum){
         this.pagination.current = 1
         parameter.pageNum = 1
       }
       let params = Object.assign(this.queryParam, parameter)
       this.loading = true;
       this.$api.recruitstat.reExamCoreLineMangegeList(params).then(res => {
         // console.log(res)
          const pagination = { ...this.pagination
         };
         pagination.total = 0
         if (res.data && res.data.total) {
           pagination.total = res.data.total;
         }
         this.data = []
         this.pagination = pagination;
         if (res.data && res.data.rows.length) {
           this.data = res.data.rows;
         }
         this.loading = false;
       })
     },
     // 分页
     handleTableChange(pagination, filters, sorter) {
       console.log(pagination);
       const pager = { ...this.pagination
       };
       pager.current = pagination.current;
       this.pagination = pager;
       this.loadData({
         pageSize: pagination.pageSize,
         pageNum: pagination.current
       });
     },
     // 多选
     onSelectChange (selectedRowKeys,selectedRows) {
       console.log('selectedRowKeys changed: ', selectedRowKeys);
       this.selectedRows = selectedRows
       this.selectedRowKeys = selectedRowKeys
     },
      // 选择院系
      yxChange(code) {
        this.$set(this.queryParam, 'zszym', '')
        this.$set(this.selectMenu, 'zy', [])
        if(code){
          this.getProssion(code)
          this.getyjfx()
        }
      },
      getProssion(code) {
        this.$api.base.majorAll({
          lsdwh: code
        }).then(res => {
          this.$set(this.selectMenu, 'zy', res.data)
        })
      },

      // 添加
      handleCreate(){
        this.secondFractionalAddVisible = true
      },
      // 修改
      handleEdit(code) {
        this.$api.recruitstat.reExamCoreLineMangegeId(code).then(res => {
          this.secondFractionalEditVisible = true
          this.secondFractionalEditData = res.data
        })
      },
      // 关闭修改
      handleEditClose(data) {
        this.secondFractionalEditVisible = false
        this.secondFractionalAddVisible = false
      },
      // 修改成功
      handleEditSuccess(data) {
        this.$message.success('修改成功')
        this.secondFractionalEditVisible = false
        this.loadData({
          pageSize:10,
          pageNum:1
        })
         this.pagination= {
          current: 1,
          pageSize:10
        }
      },
      handleAddSuccess(){
        this.$message.success('添加成功')
        this.secondFractionalAddVisible = false
        this.loadData({
          pageSize:10,
          pageNum:1
        })
        this.pagination= {
          current: 1,
          pageSize:10
        }
      },
      // 删除
      handleDel(key) {
        console.log('删除')
        var that = this;
        this.$confirm({
          title: '确定删除?',
          onOk() {
            console.log('OK');
            that.deleteData(key)
          },
          onCancel() {
            console.log('Cancel');
          },
          class: 'test',
        });
      },
      beforeUpload(file) {
        this.fileList = [...this.fileList, file]
        return false
      },
      // 导入
      handleImport(data) {
        console.log('导入')
        console.log(data)
        const {
          fileList
        } = this
        const formData = new FormData()
        formData.append('file', data.file)
        // fileList.forEach((file) => {
        //   formData.append('files[]', file)
        // })
        this.uploading = true
        this.$upload('admissions/ssfsfsx/importSsfsfsx', formData).then(res => {
          this.uploading = false
          this.$message.success('导入成功')
        })
      },
      // 批量删除
      handleBatchDel() {
        console.log('批量删除')
        var deleteId = ''
        if (!this.selectedRowKeys.length) {
          this.$message.warning('请选择需要删除的数据')
          return
        }
        if (this.selectedRows && this.selectedRows.length) {
          deleteId = this.selectedRows.map(v => {
            return v.id
          }).toString()
        }
         var that = this;
         this.$confirm({
           title: '确定批量删除?',
           onOk() {
             console.log('OK');
             that.deleteData(deleteId)
           },
           onCancel() {
             console.log('Cancel');
           },
           class: 'test',
         });
      },
      deleteData(code) {
        this.$api.recruitstat.reExamCoreLineMangegeDelete(code).then(res => {
          this.loadData({
            pageSize:10,
            pageNum:this.pagination.current
          })
          this.selectedRowKeys = []
        })
      },
      exportExcel(){
        console.log('导出')
        this.$export('admissions/ssfsfsx/download4')
      }
    }
  }
</script>

<style lang="less" scoped>
  .card {
    margin-bottom: 20px;
  }

  .ant-upload-list.ant-upload-list-text {
    display: none !important
  }
</style>
